﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

using Warehouse.Common.Entities;
using Warehouse.DataAccess;

namespace Warehouse.BusinessLogic
{
    public class UserBL : BaseBL, IUserBL
    {
        #region Singleton

        private static UserBL _instance = null;
        private static object lockObject = new object();
        public static UserBL Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (lockObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new UserBL();
                        }
                    }
                }
                return _instance;
            }
        }
        
        #endregion

        private readonly IUserDA _da;

        //--Constructor
        protected UserBL()
        {
            _da = provider.UserDA;
        }

        //C
        public User Create()
        {
            return _da.Create();
        }

        //U
        public int Add(User toUpdate, out int newID)
        {
            if (toUpdate.UserID == 0)
                return _da.Add(toUpdate, out newID);
            else
            {
                newID = toUpdate.UserID;
                return _da.Update(toUpdate);
            }
        }

        public int Update(User toUpdate)
        {
            return _da.Update(toUpdate);
        }

        //D
        public int Delete(User toDelete)
        {
            return _da.Delete(toDelete.UserID);
        }

        public int Delete(Expression<Func<User, bool>> where)
        {
            return _da.Delete(where);
        }

        //R
        public User GetByID(int id)
        {
            return _da.GetByID(id);
        }

        public User GetByCode(string code)
        {
            return _da.GetByCode(code);
        }

        public IEnumerable<User> GetList(Expression<Func<User, bool>> where)
        {
            return _da.GetList(where);
        }

        //Other
        public bool Login(string userCode, string passwd)
        {
            var user = _da.GetByCode(userCode);
            return (user != null && user.Passwd.ToUpper() == passwd.ToUpper());
        }

        public bool Logout(string userCode)
        {
            return false;
        }

        public bool ChangePasswd(User user, string oldPasswd, string newPasswd)
        {
            if (user.Passwd == oldPasswd)
            {
                user.Passwd = newPasswd;
                return (this.Update(user) > 0);
            }
            return false;
        }
    }
}
